<?php
class Pauler_Emailpdf_Model_Email_Template extends Mage_Core_Model_Email_Template{

    protected $manufacturer = array();
    protected $_itempage= array();
    /**
     * Send mail to recipient
     *
     * @param   array|string       $email        E-mail(s)
     * @param   array|string|null  $name         receiver name(s)
     * @param   array              $variables    template variables
     * @return  boolean
     **/
    public function send15($email, $name = null, array $variables = array())
    {
        if (!$this->isValidForSend()) {
            Mage::logException(new Exception('This letter cannot be sent.')); // translation is intentionally omitted
            return false;
        }

        $emails = array_values((array)$email);
        $names = is_array($name) ? $name : (array)$name;
        $names = array_values($names);
        foreach ($emails as $key => $email) {
            if (!isset($names[$key])) {
                $names[$key] = substr($email, 0, strpos($email, '@'));
            }
        }

        $variables['email'] = reset($emails);
        $variables['name'] = reset($names);

        ini_set('SMTP', Mage::getStoreConfig('system/smtp/host'));
        ini_set('smtp_port', Mage::getStoreConfig('system/smtp/port'));

        $mail = $this->getMail();

        $setReturnPath = Mage::getStoreConfig(self::XML_PATH_SENDING_SET_RETURN_PATH);
        switch ($setReturnPath) {
        case 1:
            $returnPathEmail = $this->getSenderEmail();
            break;
        case 2:
            $returnPathEmail = Mage::getStoreConfig(self::XML_PATH_SENDING_RETURN_PATH_EMAIL);
            break;
        default:
            $returnPathEmail = null;
            break;
        }

        if ($returnPathEmail !== null) {
            $mailTransport = new Zend_Mail_Transport_Sendmail("-f".$returnPathEmail);
            Zend_Mail::setDefaultTransport($mailTransport);
        }
        //Mage::log($emails);
        foreach ($emails as $key => $email) {

            $mail->addTo($email, '=?utf-8?B?' . base64_encode($names[$key]) . '?=');
        }

        $this->setUseAbsoluteLinks(true);
        $text = $this->getProcessedTemplate($variables, true);

        if($this->isPlain()) {
            $mail->setBodyText($text);
        } else {
            $mail->setBodyHTML($text);
        }

        $mail->setSubject('=?utf-8?B?' . base64_encode($this->getProcessedTemplateSubject($variables)) . '?=');
        $mail->setFrom($this->getSenderEmail(), $this->getSenderName());
        $this->addPdf( $variables['order'] );
        try {
            $mail->send();

            $this->_mail = null;
        }
        catch (Exception $e) {
            $this->_mail = null;
            //Mage::log('email faile');
            Mage::logException($e);
            return false;
        }

        return true;
    }
    public function send($email, $name = null, array $variables = array())
    {
        if (!$this->isValidForSend()) {
            Mage::logException(new Exception('This letter cannot be sent.')); // translation is intentionally omitted
            return false;
        }

        $emails = array_values((array)$email);
        $names = is_array($name) ? $name : (array)$name;
        $names = array_values($names);
        foreach ($emails as $key => $email) {
            if (!isset($names[$key])) {
                $names[$key] = substr($email, 0, strpos($email, '@'));
            }
        }

        $variables['email'] = reset($emails);
        $variables['name'] = reset($names);

        ini_set('SMTP', Mage::getStoreConfig('system/smtp/host'));
        ini_set('smtp_port', Mage::getStoreConfig('system/smtp/port'));

        $mail = $this->getMail();

        $setReturnPath = Mage::getStoreConfig(self::XML_PATH_SENDING_SET_RETURN_PATH);
        switch ($setReturnPath) {
        case 1:
            $returnPathEmail = $this->getSenderEmail();
            break;
        case 2:
            $returnPathEmail = Mage::getStoreConfig(self::XML_PATH_SENDING_RETURN_PATH_EMAIL);
            break;
        default:
            $returnPathEmail = null;
            break;
        }

        if ($returnPathEmail !== null) {
            $mailTransport = new Zend_Mail_Transport_Sendmail($returnPathEmail);
            Zend_Mail::setDefaultTransport($mailTransport);
        }

        foreach ($emails as $key => $email) {
            $mail->addTo($email, '=?utf-8?B?' . base64_encode($names[$key]) . '?=');
        }

        $this->setUseAbsoluteLinks(true);
        $text = $this->getProcessedTemplate($variables, true);

        if($this->isPlain()) {
            $mail->setBodyText($text);
        } else {
            $mail->setBodyHTML($text);
        }

        $mail->setSubject('=?utf-8?B?' . base64_encode($this->getProcessedTemplateSubject($variables)) . '?=');
        $mail->setFrom($this->getSenderEmail(), $this->getSenderName());
        $this->addPdf( $variables['order'] );
        try {
            $mail->send();
            $this->_mail = null;
        }
        catch (Exception $e) {
            $this->_mail = null;
            Mage::logException($e);
            return false;
        }

        return true;
    }
    public function addPdf($order){

        $itemGroup = array();
        foreach($order->getItemsCollection() as $item){
            $product = Mage::getModel('catalog/product')->load($item->getProductId());
            if(Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty()>0){
                //echo 'in:'.$item->getProductId().'-'.$product->getManufacturer().'<br/>';
                $itemGroup['in'][$product->getManufacturer()][] = $item;
            }else{
                // echo 'out:'.$item->getProductId();
                $itemGroup['out'][$product->getManufacturer()][] = $item; 
            } 
        }
        //
        $cvsFile = Mage::getBaseDir('var').DS.'manufacturer.csv';
        $file = fopen($cvsFile,'r');
        while ($data = fgetcsv($file)) {    //每次读取CSV里面的一行内容  
           // print_r($data); //此为一个数组，要获得每一个数据，访问数组下标即可
            $this->manufacturer[$data['0']] = $data;
        }
        //echo '<pre>';var_dump($manufacturer);
        //
        foreach( $itemGroup['in'] as $key=>$items){
            $this->productpdf($items,$key,'in',$order);
        }
        foreach( $itemGroup['out'] as $key=>$items){
            $this->productpdf($items,$key,'out',$order);
        }
        unset($page); 
    }
    /**
     * 添加附件
     * */
    public function publicPdf($order){
        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
        //echo $order->getRealOrderId(),'<br/>',$order->getCreatedAtDate(),'<br/>',$order->getCreatedAtStoreDate(),'<br/>'.$order->getCustomerName(),'<br/>'.$order->getShippingAddress()->getFormated(true);
        //送货地址
        $address = $order->getShippingAddress();
        $formater   = new Varien_Filter_Template();
        $attributes = Mage::helper('customer/address')->getAttributes();
        $dataFormat = Mage_Customer_Model_Attribute_Data::OUTPUT_FORMAT_PDF;
        $data = array();
        foreach ($attributes as $attribute) {
            /* @var $attribute Mage_Customer_Model_Attribute */
            if (!$attribute->getIsVisible()) {
                continue;
            }
            if ($attribute->getAttributeCode() == 'country_id') {
                $data['country'] = $address->getCountryModel()->getName();
            } else if ($attribute->getAttributeCode() == 'region') {
                $data['region'] = $address->getRegion();
            } else {
                $dataModel = Mage_Customer_Model_Attribute_Data::factory($attribute, $address);
                $value     = $dataModel->outputValue($dataFormat);
                if ($attribute->getFrontendInput() == 'multiline') {
                    $values    = $dataModel->outputValue(Mage_Customer_Model_Attribute_Data::OUTPUT_FORMAT_ARRAY);
                    // explode lines
                    foreach ($values as $k => $v) {
                        $key = sprintf('%s%d', $attribute->getAttributeCode(), $k + 1);
                        $data[$key] = $v;
                    }
                }
                $data[$attribute->getAttributeCode()] = $value;
            }
        }
        //unset($data['firstname']);
        // unset($data['lastname']);
        // $formater->setVariables($data);
        //$countryFormat = $address->getCountryModel()->getFormat('pdf');
        // $format = $countryFormat ? $countryFormat->getFormat() : $address->getConfig()->getFormatByCode('pdf')->getRenderer()->getType()->getDefaultFormat();

        // var_dump($formater->filter($format));
        $address_str = $data['company'].','.$data['street'].' '.$data['city'].','.$data['postcode'].','.$data['country'];
        $tel = $data['telephone'];
        //echo '<pre>' ;var_dump($data);

        // $_order->getShippingAddress()->getFormated(true)
        // $orderAdminDate = $this->formatDate($_order->getCreatedAtDate(), 'medium', true);
        //$orderStoreDate = $this->formatDate($_order->getCreatedAtStoreDate(), 'medium', true); 
        //$pdf = new Zend_Pdf();
        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
        $height = $page->getHeight();
        $width = $page->getWidth();
        //$pdf->pages[] = $page;
        //创建字体
        $style = new Zend_Pdf_Style();
        $size = 10;
        //$font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/LinLibertineFont/LinLibertine_Bd-2.8.1.ttf');
        $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);

        $style->setFont($font, $size);
        //end style font
        //insert logo
        $store = $order->getStoreId(); 
        $image = Mage::getStoreConfig('sales/identity/logo', $store);
        // var_dump($image);
        if ($image) {
            $image = Mage::getStoreConfig('system/filesystem/media', $store) . '/sales/store/logo/' . $image;
            if (is_file($image)) {
                $image = Zend_Pdf_Image::imageWithPath($image);
                 $page->drawImage($image, 425, $height-72, 535, $height-27);
            }
        }
        $begin = 42;
        //URGENT FAX ORDER
        $page->setFont($font,20)->drawText('URGENT FAX ORDER - ',$begin,$height-132);
        $page->setFont($font,20)->drawText($order->getRealOrderId(),$begin+220,$height-132);
        $page->setFont($font,15)->drawText('Supplier:',$begin,$height-185);
        $page->setFont($font,15)->drawText('Delivery Details:',263,$height-185);
        $page->setFont($font,12)->drawText( $order->getCustomerName(),263,$height-200);
        //$page->setFont($font,15)->drawText( $address_str,263,$height-225);
        //$data['street'].' '.$data['city'].','.$data['postcode'].','.$data['country']; 
        $page->drawText( $data['street'],263,$height-215);
        $page->drawText( $data['city'],263,$height-230);
        $page->drawText( $data['postcode'],263,$height-245);
        $page->drawText( $data['country'],263,$height-260); 
        $page->drawText( $tel,263,$height-275);
        $page->setFont($font,12)->drawText('Date:',$begin,$height-314);
        $page->drawText($order->getCreatedAtDate(),$begin+37,$height-314);
        $page->setFont($font,12)->drawText('Initial:',363,$height-314);
        $page->setFont($font,12)->drawText($order->getRealOrderId(),363,$height-294);
        $page->setLineColor(new Zend_Pdf_Color_Rgb(0,0,0));
        $page->drawLine(400, $height-314, 466,$height-314);

        $page->setLineWidth(3.5)->drawLine($begin, $height-351, $width-65,$height-351);
        $page->drawText('Please process the following order and arrange delivery direct to the ',$begin,$height-378);
        $page->drawText('customer for _ _ _ _ _ _ _ _ _ (details above).Please confirm delivery details.',$begin,$height-396); 
        $page->drawText('Thanks,',$begin,219);
        $page->drawText('_ _ _ _ _ _ _ _ _ _ _',$begin,176);
        $page->drawText('The Radiator Gallery',$begin,159); 
        $page->setLineWidth(1);
        $page->drawText('_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _',$begin,135);

        // set line color
        $page->setLineColor(new Zend_Pdf_Color_Rgb(0,0,0));
        // draw a face
        $page->drawRectangle($begin, 93, $width-65, 76, Zend_Pdf_Page::SHAPE_DRAW_STROKE);
        $page->drawText('The  Radiator  Gallery  Ltd.  140  Hermon  Hill, South  Woodford, London,  E18  1QH',$begin,60);
        $page->setFont($font,10)->drawText('   Tel:020  8530  7555  FAX:020  8530  8844  Email:  info@theradiatorgallery.com',$begin,48);
        $page->setFont($font,8)->drawText('The Radiator Gallery Ltd - Company  Registration  No.  6235885 - Registered  Office: 158 Hermon Hill, London, E18 1QH',$begin,36);
        return $page;

    }
    public function productpdf($items,$key,$stock,$order){
        $pdf = new Zend_Pdf();
        $page = $this->publicPdf($order);
        $pdf->pages[] = $page;
        $page->setLineWidth(1);
        $height = $page->getHeight();
        $width = $page->getWidth();
        $begin = 42;
        $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
        $tableBeginx = 42;
        $tableBeginY = $height- 431;
        $tableEndx = $width-65;
        $rowHeight = 22;
        $cols = array('40','226','112','52',52);
        $colsWord = array('QTY','PRODUCT NAME','COLOUR','WIDTH','HEIGHT');
        $colsKey = array('qty','name','colour','width','height');
        $rows = count($items)+1;
        $code='manufacturer';
        $object = new Varien_Object;
        $object->setData($code,$key);
        $ManufacturerName = Mage::getModel('catalog/product')->getResource()->getAttribute($code)->getFrontend()->getValue($object);
        $page->setFont($font,15)->drawText($ManufacturerName,$begin,$height-213);
        if($this->manufacturer[$ManufacturerName][1]){
            $page->setFont($font,15)->drawText($this->manufacturer[$ManufacturerName][1],$begin,$height-233);
        }
        if($this->manufacturer[$ManufacturerName][2]){
            $page->setFont($font,15)->drawText($this->manufacturer[$ManufacturerName][2],$begin,$height-253);
        }

        for($i=0;$i<=$rows;$i++){
            $rowEndY = $rowBeginY = $tableBeginY - ($i-1)*$rowHeight;
            $page->drawLine($tableBeginx,$rowBeginY, $tableEndx,$rowEndY);
            if($i==$rows){break;}
            $colx = $tableBeginx;
            $page->drawLine($colx,$rowEndY, $colx,$rowEndY-$rowHeight);
            $j=0;
            $colsAmount = count($cols);
            if($i!=0){
                $item = $items[$i-1];
                $product = Mage::getModel('catalog/product')->load($item->getProductId());
            }
            foreach($cols as $col){
                if($i==0){
                    $page->setFont($font,10)->drawText($colsWord[$j],$colx+6,$rowEndY-15);
                }else{ 
                    switch($colsKey[$j]){
                    case 'qty':
                        $text = $item->getQtyOrdered()*1;break;
                    case 'name':
                        $text = $product->getResource()->getAttribute('pdf_name')?$product->getResource()->getAttribute('pdf_name')->getFrontend()->getValue($product):'NULL';break;
                    case 'code':
                        $text = $product->getProductCode();break;
                    case 'colour':
                        $text = $product->getResource()->getAttribute('config_finish')->getFrontend()->getValue($product);break;
                    case 'width':
                        $text =  $product->getWidth();break;
                    case 'height':
                        $text = $product->getHeight();break;


                    }
                    $page->setFont($font,8)->drawText($text,$colx+6,$rowEndY-15);

                }
                $j++;
                $colx+= $col; 
                if($colx >$tableEndx || $j==$colsAmount) $colx = $tableEndx;
                $page->drawLine($colx,$rowEndY, $colx,$rowEndY-$rowHeight);


            }
        }
        if($stock=='in'){
            $name = 'Packing-Slip-'.$order->getIncrementId().'-'.$key.'.pdf';
        }else{
            $name = 'FAX-'.$order->getIncrementId().'-'.$key.'.pdf';
        }
        $this->addAttachment($pdf,$name);
        $this->savePdf($pdf,$name); 

    }
    public function addAttachment(Zend_Pdf $pdf,$attname){
        $file = $pdf->render(); 
        $attachment = $this->getMail()->createAttachment($file);
        $attachment->type = 'application/pdf';
        $attachment->filename = $attname;
    }
    public function savePdf(Zend_Pdf $pdf,$name){
        $dir = Mage::getBaseDir('var').DS.'orderpdf'.DS;
        if( !is_dir($dir) && !@mkdir($dir,0777)){
            $dir = Mage::getBaseDir('var').DS;
        }
        if(is_dir($dir)){
            $file = $dir.$name; 
            @$pdf->save($file);
        }     
    } 

}
